﻿using System;
using System.Activities;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Wicresoft.AppFlow.Flows;
using AppLab.Data.Models;

namespace Wicresoft.AppFlow.Activities
{
    public sealed class Submit : CodeActivity
    {
        // Define an activity input argument of type string
        public InArgument<SubmitData> Entity { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            var data = context.GetValue(this.Entity) as SubmitData;
            var e = data.ToDatabaseFormat() as tysx_Submit;
            Debug.Assert(e != null, "Entity object [tysx_Submit] cannot be null");

            // Workflow的参数不能使用EntityObject，否则在持久化的时候需要一个打开的
            //  ObjectContext对象，这使得代码层不能使用using来Dispose它。
            //  所以，最后使用一个自定义对象SubmitData来作为参数传入
            using (var dc = PMSEntities.Create())
            {
                dc.tysx_Submit.AddObject(e);
                //安装包
                dc.tysx_MediaClient.AddObject(e.tysx_MediaClient);

                if (e.tysx_UpgradeMediaClient != null)
                {
                    dc.tysx_UpgradeMediaClient.AddObject(e.tysx_UpgradeMediaClient);
                }

                dc.SaveChanges();

                var flow = new tysx_AppFlow()
                {
                    SubmitID = e.SubmitID,
                    FlowID = context.WorkflowInstanceId,
                    StateID = (int)FlowState.PendingReview,
                };
                dc.tysx_AppFlow.AddObject(flow);
                dc.SaveChanges();
            }
        }
    }
}
